package by.koleda.photoupdater.provider;

import java.util.ArrayList;

import android.content.ContentProvider;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.OperationApplicationException;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import by.koleda.photoupdater.provider.PhotoContract.PhotoColumns;
import by.koleda.photoupdater.provider.PhotoContract.Suggestions;
import by.koleda.photoupdater.provider.PhotoDatabase.Tables;

public class PhotoProvider extends ContentProvider {

	private static final UriMatcher sUriMatcher = buildUriMatcher();

	private static final int VKCONTACTS = 100;
	private static final int VKCONTACTS_ID = 101;
	
	private static final int SUGGESTIONS = 200;
	private static final int SUGGESTIONS_ID = 201;

	private static UriMatcher buildUriMatcher() {
		final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
		final String authority = PhotoContract.CONTENT_AUTHORITY;

		matcher.addURI(authority, "vkcontacts", VKCONTACTS);
		matcher.addURI(authority, "vkcontacts/*", VKCONTACTS_ID);
		matcher.addURI(authority, "suggestions", SUGGESTIONS);
		matcher.addURI(authority, "suggestions/*", SUGGESTIONS_ID);
		return matcher;
	}

	private PhotoDatabase photoDatabase;

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		final SQLiteDatabase db = photoDatabase.getWritableDatabase();
		int deleteCount = 0;
		final int match = sUriMatcher.match(uri);
		switch (match) {
			case VKCONTACTS: {
				deleteCount = db.delete(Tables.VKCONTACTS, selection, selectionArgs);
				break;
			}
			case VKCONTACTS_ID: {
				String idStr = uri.getLastPathSegment();
				String where = PhotoColumns._ID + " = " + idStr;
				if (!TextUtils.isEmpty(selection)) {
					where += " AND " + selection;
				}
				deleteCount = db.delete(Tables.VKCONTACTS, where, selectionArgs);
				break;
			}
			case SUGGESTIONS: {
				deleteCount = db.delete(Tables.SUGGESTIONS, selection, selectionArgs);
				break;
			}
			case SUGGESTIONS_ID: {
				String idStr = uri.getLastPathSegment();
				String where = Suggestions._ID + " = " + idStr;
				if (!TextUtils.isEmpty(selection)) {
					where += " AND " + selection;
				}
				deleteCount = db.delete(Tables.SUGGESTIONS, where, selectionArgs);
				break;
			}
			default:
				throw new IllegalArgumentException("Unsupported URI: " + uri);
		}
		if (deleteCount > 0) {
			getContext().getContentResolver().notifyChange(uri, null);
		}
		return deleteCount;
	}

	@Override
	public String getType(Uri uri) {
		final int match = sUriMatcher.match(uri);
		switch (match) {
		case VKCONTACTS:
			return PhotoContract.PhotoColumns.CONTENT_TYPE;
		case VKCONTACTS_ID:
			return PhotoContract.PhotoColumns.CONTENT_ITEM_TYPE;
		case SUGGESTIONS:
			return PhotoContract.Suggestions.CONTENT_TYPE;
		case SUGGESTIONS_ID:
			return PhotoContract.Suggestions.CONTENT_ITEM_TYPE;
		default:
			throw new UnsupportedOperationException("Unknown uri: " + uri);
		}
	}

	public Uri insert(Uri uri, ContentValues values) {

		final SQLiteDatabase db = photoDatabase.getWritableDatabase();
		final int match = sUriMatcher.match(uri);
		switch (match) {
			case VKCONTACTS: {
				long id = db.insertOrThrow(Tables.VKCONTACTS, null, values);
				getContext().getContentResolver().notifyChange(uri, null);
				Uri insertionUri = ContentUris.withAppendedId(PhotoContract.PhotoColumns.CONTENT_URI, id);
				return insertionUri;
			}
			case SUGGESTIONS: {
				long id = db.insertOrThrow(Tables.SUGGESTIONS, null, values);
				getContext().getContentResolver().notifyChange(uri, null);
				Uri insertionUri = ContentUris.withAppendedId(PhotoContract.Suggestions.CONTENT_URI, id);
				return insertionUri;
			}
			default: {
				throw new UnsupportedOperationException("Unknown uri: " + uri);
			}
		}
	}

	@Override
	public boolean onCreate() {
		photoDatabase = new PhotoDatabase(getContext());
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		final SQLiteDatabase db = photoDatabase.getReadableDatabase();
		SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
		final int match = sUriMatcher.match(uri);
		switch (match) {
			case VKCONTACTS:
				builder.setTables(Tables.VKCONTACTS);
				break;
			case VKCONTACTS_ID:
				builder.setTables(Tables.VKCONTACTS);
				builder.appendWhere(PhotoColumns._ID + " = " + uri.getLastPathSegment());
				break;
			case SUGGESTIONS:
				builder.setTables(Tables.SUGGESTIONS);
				break;
			case SUGGESTIONS_ID:
				builder.setTables(Tables.SUGGESTIONS);
				builder.appendWhere(Suggestions._ID + " = " + uri.getLastPathSegment());
				break;
			default:
				throw new IllegalArgumentException("Unsupported URI: " + uri);
		}
		Cursor cursor = builder.query(db, projection, selection, selectionArgs, null, null, sortOrder);
		cursor.setNotificationUri(getContext().getContentResolver(), uri);
		return cursor;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		final SQLiteDatabase db = photoDatabase.getWritableDatabase();
		int updateCount = 0;
		final int match = sUriMatcher.match(uri);
		switch (match) {
			case VKCONTACTS: {
				updateCount = db.update(Tables.VKCONTACTS, values, selection, selectionArgs);
				break;
			}
			case VKCONTACTS_ID: {
				String idStr = uri.getLastPathSegment();
				String where = PhotoColumns._ID + " = " + idStr;
				if (!TextUtils.isEmpty(selection)) {
					where += " AND " + selection;
				}
				updateCount = db.update(Tables.VKCONTACTS, values, where, selectionArgs);
				break;
			}
			case SUGGESTIONS: {
				updateCount = db.update(Tables.SUGGESTIONS, values, selection, selectionArgs);
				break;
			}
			case SUGGESTIONS_ID: {
				String idStr = uri.getLastPathSegment();
				String where = Suggestions._ID + " = " + idStr;
				if (!TextUtils.isEmpty(selection)) {
					where += " AND " + selection;
				}
				updateCount = db.update(Tables.SUGGESTIONS, values, where, selectionArgs);
				break;
			}
			default:
				throw new IllegalArgumentException("Unsupported URI: " + uri);
		}
		if (updateCount > 0) {
			getContext().getContentResolver().notifyChange(uri, null);
		}
		return updateCount;
	}

	@Override
	public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
			throws OperationApplicationException {
		final SQLiteDatabase db = photoDatabase.getWritableDatabase();
		db.beginTransaction();
		try {
			final int numOperations = operations.size();
			final ContentProviderResult[] results = new ContentProviderResult[numOperations];
			for (int i = 0; i < numOperations; i++) {
				results[i] = operations.get(i).apply(this, results, i);
			}
				db.setTransactionSuccessful();
				return results;
		} finally {
			db.endTransaction();
		}
	}
	
	
}
